package client.global.commlib.network.converterfactory

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Converter.Factory
import retrofit2.Retrofit
import java.lang.reflect.Type

class CustomGsonConverterFactory : Factory() {
    /**
     * Create an instance using a default [Gson] instance for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */


    lateinit var gson: Gson

    override fun responseBodyConverter(
        type: Type?, annotations: Array<Annotation?>?, retrofit: Retrofit?
    ): Converter<ResponseBody?, Any?>? {
        val adapter = gson!!.getAdapter(TypeToken.get(type)) as TypeAdapter<Any>
        return CustomGsonResponseConverter(gson, adapter) as Converter<ResponseBody?, Any?>
    }

    override fun requestBodyConverter(
        type: Type?,
        parameterAnnotations: Array<Annotation?>?,
        methodAnnotations: Array<Annotation?>?,
        retrofit: Retrofit?
    ): Converter<*, RequestBody?>? {
        val adapter = gson!!.getAdapter(TypeToken.get(type)) as TypeAdapter<Any>
        return CustomGsonRequestBodyConverter(gson, adapter)
    }
}